package com.temp.controller.admin;

import com.temp.dto.SearchUserDTO;
import com.temp.dto.UserDTO;
import com.temp.entity.User;
import com.temp.exception.BaseException;
import com.temp.result.Result;
import com.temp.service.UserService;
import com.temp.utils.PasswordHelper;
import com.temp.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/admin/user")
@Api(tags = "管理用户相关接口")
@Slf4j
@Validated
public class AdminUserController {

    @Autowired
    private UserService userService;

    @PostMapping("/query")
    @ApiOperation("管理员查询用户信息")
    @RequiresPermissions("admin:user:query")
    public Result getAllUsers(@RequestBody SearchUserDTO searchUserDTO) {
        searchUserDTO.formatParam();
        return Result.success(userService.findAllUserDetail(searchUserDTO),"apiMsg.querySuccess");
    }

    @PostMapping("/updateOrSave")
    @ApiOperation("管理员保存或者更新用户")
    @RequiresPermissions("admin:user:updateOrSave")
    public Result<String> updateOrSave(@Valid @RequestBody UserDTO userDTO) {
        validateUserDTO(userDTO);
        User user = convertToUser(userDTO);
        boolean isSuccess = userService.saveOrUpdate(user);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除用户")
    @RequiresPermissions("admin:user:delete")
    public Result delUser(@RequestParam Long id) {
        boolean isSuccess = userService.removeById(id);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }

    /**
     * 验证用户DTO
     */
    private void validateUserDTO(UserDTO userDTO) {
        // 新用户验证
        if (ObjectUtils.isEmpty(userDTO.getId())) {
            if (StringUtils.isBlank(userDTO.getPassword())) {
                throw new BaseException("apiMsg.newUserNotPW");
            }
            if (StringUtils.isBlank(userDTO.getUsername())) {
                throw new BaseException("apiMsg.newUserNotName");
            }
            if (StringUtils.isBlank(userDTO.getEmail())) {
                throw new BaseException("apiMsg.newUserNotEmail");
            }
        }
    }

    /**
     * 转换DTO到实体
     */
    private User convertToUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 密码处理
        if (StringUtils.isNotBlank(userDTO.getPassword())) {
            String salt = PasswordHelper.generateSalt();
            user.setSalt(salt);
            user.setPasswordHash(PasswordHelper.encryptPassword(userDTO.getPassword(), salt));
        }

        return user;
    }
}
